package ru.reaperoq.inventory.screens.main.admin.users

import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import models.shared.UserUi
import ru.reaperoq.inventory.components.textField.DropDownTextField

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChangeUserRoleDialog(
    modifier: Modifier = Modifier,
    userUi: UserUi,
    onDismiss: () -> Unit,
    onConfirm: (id: Int, role: UserUi.Role) -> Unit
) {
    var roleName by remember(userUi.role, userUi.username) {
        mutableStateOf(
            when (userUi.role) {
                UserUi.Role.ADMIN -> "Администратор"
                UserUi.Role.USER -> "Пользователь"
                UserUi.Role.MODERATOR -> "Модератор"
            }
        )
    }
    val selectedRole by remember(roleName) {
        mutableStateOf(
            when (roleName) {
                "Администратор" -> UserUi.Role.ADMIN
                "Пользователь" -> UserUi.Role.USER
                "Модератор" -> UserUi.Role.MODERATOR
                else -> UserUi.Role.USER
            }
        )
    }
    val data = listOf(
        "Администратор",
        "Пользователь",
        "Модератор"
    )

    AlertDialog(
        modifier = modifier,
        onDismissRequest = onDismiss,
        title = {
            Text(buildAnnotatedString {
                append("Изменить роль ")
                withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
                    append(userUi.username)
                }
            })
        },
        text = {
            DropDownTextField(
                data = data,
                value = roleName,
                labelText = "Роль",
                readOnly = true,
            ) {
                roleName = it
            }
        },
        dismissButton = {
            Button(onClick = onDismiss) {
                Text("Отмена")
            }
        },
        confirmButton = {
            TextButton(onClick = {
                if (roleName.isEmpty()) {
                    // error = true
                } else {
                    onConfirm(userUi.id, selectedRole)
                    onDismiss()
                }
            }) {
                Text("Сохранить")
            }
        }
    )
}